package com.ys.controller.api.business;

import com.ys.vo.R;
import com.ys.config.MenuId;
import com.ys.entity.business.TpProductBasis;
import com.ys.entity.business.TpProductBq;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.TpProductBasicComponentService;
import com.ys.service.business.TpProductBasicService;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tpProductBasis")
public class ApiInterTpProductBasisController {

	private static final Logger logger = LoggerFactory.getLogger(ApiInterTpProductBasisController.class);


	@Autowired
	private CommonApiService<TpProductBasis> commonApiService;
	@Autowired
	private TpProductBasicService tpProductBasicService;
	@Autowired
	private TpProductBasicComponentService tpProductBasicComponentService;

	@Autowired
	private YsbExportLogService ysbExportLogService;

	/**
	 * 查询
	 * @param model
	 * @param request
	 * @param response
	 * @param cond
	 * @return
	 */
	@RequiresPermissions("tpProductBasis:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TpProductBasis cond
			){
		cond.addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id");
		cond.addField("t2.UserName as createUser, t2.DeptName as createDeptName,t2.RoleName as createPosition")
		.addLeftJoin("TB_BaseinfoSppl D ON  D.id = A.CommodityPlId")
		.addLeftJoin("TB_BaseinfoSppm W ON  W.id = A.NameId")
		.addLeftJoin("TB_BaseinfoSpyt H ON  H.id = A.UsageId")
		.addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.VGsBm = A.VgsBm")
		.addField("D.categoryCn AS commodityPl")
		.addField("W.NameCn AS nameCn,W.NameEn AS nameEn ")
		.addField("H.UsageCn AS usageCn,H.UsageEn AS usageEn ")
		.addField("THRO.CUser AS cUser,THRO.VGsMc AS vgsMc,THRO.VGsJc AS vgsJc")
		.addField("STUFF((SELECT ',' + tpm.MaterialNameCn FROM TP_ProductMaterial tpm WHERE tpm.Type = 2 AND tpm.ProductCode = A.Code ORDER BY tpm.MaterialNameCn FOR XML PATH('')), 1, 1, '') AS materialCn");

		//权限
        cond = commonApiService.dataAuth(MenuId.TP_ProductBasis, cond);

		cond.setOrderby("A.CreateTime DESC");
		return commonApiService.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request,
			@RequestParam Map<String, Object> params){

		return tpProductBasicService.add(params);
	}
	
	/**
	 * 修改
	 */
	@PostMapping("/edit")
    @ResponseBody
	public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params,
			String sonlist){
		try {
			return tpProductBasicService.edit(params, sonlist);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}

	}

	//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/search2")
	@ResponseBody
	public LayuiTableVoJA search2(Model model, HttpServletRequest request, HttpServletResponse response,
								 @ModelAttribute TpProductBasis cond
	){

		cond.addField("(A.code +'--'+ A.name) aaa");


		return commonApiService.searchLay(cond);
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("tpProductBasis:delete")
	@PostMapping("/deleteTrue")
	@ResponseBody
	public R deleteTrue(HttpServletRequest request, @RequestParam Map<String, Object> params) {

		try {
			//删除
			for(int i=0;i<params.size();i++){
				tpProductBasicService.deleteTpProductBasic(params);
			}
			return R.ok("删除成功!");
		}catch (Exception e){
			e.printStackTrace();
			return R.error("删除失败，请稍后重试！");
		}
	}
	
	/**
	 * 新增商品子件
	 */
	@PostMapping("/addComponent")
    @ResponseBody
	public R addComponent(HttpServletRequest request, String pcode){

		return tpProductBasicComponentService.add(pcode);
	}


	/**
	 * 商品库变体新增弹框列表使用
	 * @param model
	 * @param request
	 * @param response
	 * @param cond
	 * @return
	 */
	@RequestMapping("/searchBt")
	@ResponseBody
	public LayuiTableVoJA searchBt(Model model, HttpServletRequest request, HttpServletResponse response,
								  @ModelAttribute TpProductBasis cond
	){

//		cond.where("A.IsSuperior = '是'");
		cond.addField("THRO.CUser AS cUser");
		cond.addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.VGsBm = A.VgsBm");
		//权限
		cond = commonApiService.dataAuth(MenuId.TP_ProductBasis, cond);

		return commonApiService.searchLay(cond);
	}

	/**
	 * 商品库优品新增弹框列表使用
	 * @param model
	 * @param request
	 * @param response
	 * @param cond
	 * @return
	 */
	@RequestMapping("/searchYp")
	@ResponseBody
	public LayuiTableVoJA searchYp(Model model, HttpServletRequest request, HttpServletResponse response,
								   @ModelAttribute TpProductBasis cond
	){

		cond.addField("THRO.CUser AS cUser");
		cond.addLeftJoin("THR_OperateCompanyApply THRO ON  THRO.VGsBm = A.VgsBm");
		cond.where("A.IsSuperior = '否' AND A.vsfJp = '否'");
		//权限
		cond = commonApiService.dataAuth(MenuId.TP_ProductBasis, cond);

		return commonApiService.searchLay(cond);
	}


	@RequestMapping("/export")
	@ResponseBody
	public com.ys.vo.R export(@ModelAttribute TpProductBasis cond, String conditions) throws Exception{
		YsbExportLogService.ExportDto dto1 = ysbExportLogService.init(MenuId.TP_ProductBasis);
		try {
			cond.setPage(0).setSize(999999);

			cond.addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id");
			cond.addField("t2.UserName as createUser, t2.DeptName as createDeptName,t2.RoleName as createPosition")
			.addLeftJoin("TB_BaseinfoSppl D ON  D.id = A.CommodityPlId")
			.addLeftJoin("TB_BaseinfoSppm W ON  W.id = A.NameId")
			.addLeftJoin("TB_BaseinfoSpyt H ON  H.id = A.UsageId")
			.addLeftJoin("THR_OperateCompanyBeian M ON  M.Code = A.VgsBm")
			.addField("D.categoryCn AS commodityPl")
			.addField("W.NameCn AS nameCn,W.NameEn AS nameEn ")
			.addField("H.UsageCn AS usageCn,H.UsageEn AS usageEn ")
			.addField("M.FullName AS vgsMc,M.Name AS vgsJc")
			.addField("STUFF((SELECT ',' + tpm.MaterialNameCn FROM TP_ProductMaterial tpm WHERE tpm.Type = 2 AND tpm.ProductCode = A.Code ORDER BY tpm.MaterialNameCn FOR XML PATH('')), 1, 1, '') AS materialCn");

			cond.setOrderby("A.CreateTime DESC");

			List<Map<String, Object>> listData = cond.queryMap();



			List<YsCol> listField = new YsCol()
					.setMenuId(MenuId.TP_ProductBasis)
					.setFrontShow(YsColEnum.FrontShow.SHOW.value)
					.setOrderby("A.SortNo asc")
					.queryList();

			ExportExcelUtils<TpProductBq> util = new ExportExcelUtils<TpProductBq>(new TpProductBq());

			String toFilePath = util.exportExcel(listData, listField, "商品表");
			UploadService.UploadDto dto2 = commonApiService.uploadLocalToServer(toFilePath);
			ysbExportLogService.updateSuccess(dto1.getId(), dto2.getUrl());
			return com.ys.vo.R.ok("已经生成完毕");
		}catch (Exception e){
			ysbExportLogService.updateFail(dto1.getId());
			return com.ys.vo.R.error("生成失败，请联系客服");
		}
	}



	/**
	 * 商品库批量导入
	 */
	@RequestMapping("/importInfoFromBatchImportLogByMain")
	@ResponseBody
	public void importInfoFromBatchImportLogByMain(Model model, HttpServletRequest request, HttpServletResponse response
	){
		try {
			tpProductBasicService.importInfoFromBatchImportLogByMain();
		}catch (Exception e){
			logger.error("出错：",e.getMessage(),e);
		}
	}





	/**
	 * 商品库子件批量导入
	 */
	@RequestMapping("/importInfoFromBatchImportLogBySub")
	@ResponseBody
	public void importInfoFromBatchImportLogBySub(Model model, HttpServletRequest request, HttpServletResponse response
	){
		try {
			tpProductBasicService.importInfoFromBatchImportLogBySub();
		}catch (Exception e){
			logger.error("出错：",e.getMessage(),e);
		}
	}






}
